﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class LG_InvFlowInterfaceBusiness : LGInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption LG_Query;
        public LG_InvFlowInterfaceBusiness()
        {
            this.InterfaceName = "库存流水查询";
            //索引字段
            this.MapFields = GetMapField("LG_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            LG_Query = this.interfaceOption.Where(x => x.OperateType == "LG_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LG_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, LG_NoQueryEventArgs LG_NoQueryEventArgs)
        {
            //API请求是否成功
            LG_NoQueryEventArgs.Success = LG_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, LG_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取appId
                var key = JObject.Parse(LG_Query.TargetLoginData);
                queryEventArgs.UrlQuery.UserName = key["username"].Value<string>();
                queryEventArgs.UrlQuery.Password = key["password"].Value<string>();
                queryEventArgs.UrlQuery.AccountType = key["accountType"].Value<string>();
                queryEventArgs.UrlQuery.AccessKey = key["accessKey"].Value<string>();
                queryEventArgs.UrlQuery.SecrectKey = key["secrectKey"].Value<string>();
                //获取token
                string token = GetToken(queryEventArgs.UrlQuery.UserName, queryEventArgs.UrlQuery.Password, queryEventArgs.UrlQuery.AccountType);
                LG_TokenDTO result = (LG_TokenDTO)JsonConvert.DeserializeObject<LG_TokenDTO>(token);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", result.data.tokenHead + result.data.token);
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                //设置查询的页索引
                queryEventArgs.Page.PageIndex = 1;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, LG_QueryEventArgs queryEventArgs)
        {
            if (!queryEventArgs.Page.Complete)
            {
                //获取请求的数据
                Inv_ReqDTO data = new Inv_ReqDTO();
                data.pageNum = queryEventArgs.Page.PageIndex;
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
                var reqData = JObject.Parse(queryEventArgs.reqData);
                //获取所有json节点的信息
                var nodes = queryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == LG_Query.Id);
                //需要将请求的数据拼接到url中，先转换成字典
                Dictionary<string, object> reqKeyValue = new Dictionary<string, object>();
                foreach (var item in nodes)
                {
                    if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                    {
                        reqKeyValue.Add(item.TargetField, reqData[item.TargetField].ToString());
                    }
                }
                //获取编码后的URL
                string url = GetEncodeUrl(LG_Query.TargetUrl, queryEventArgs.UrlQuery.AccessKey, queryEventArgs.UrlQuery.SecrectKey, reqKeyValue);
                queryEventArgs.HttpClient.Url = url;
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, LG_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                LGResponeDTO<LGInvFlow> result = (LGResponeDTO<LGInvFlow>)JsonConvert.DeserializeObject<LGResponeDTO<LGInvFlow>>(queryEventArgs.ResultStr);
                if (result.success)
                {
                    queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }

                //数据读取完成
                if (result.data.list.Count < 200)
                {
                    queryEventArgs.Page.Complete = true;
                }
                else
                {
                    queryEventArgs.Page.PageIndex += 1;
                }
                queryEventArgs.Rows = result.data.list;
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<LGInvFlow> QQ = await this.QueryAsync<LGInvFlow>(this.LG_Query, SqlDb);
            //QQ.ForEach(x => x.ID = x.amazon_order_id);
            //var ww1 = QQ.GroupBy(x => x.ID).Where(x => x.Count() > 1);
            var ww = QQ.GroupBy(r => r.id).Select(g => g.FirstOrDefault()).ToList();
        }

        /// <summary>
        /// 获取参数编译后的URL
        /// </summary>
        /// <param name="url"></param>
        /// <param name="access_token"></param>
        /// <param name="app_key"></param>
        /// <param name="reqData"></param>
        /// <returns></returns>
        public string GetEncodeUrl(string url, string accessKey, string secrectKey, Dictionary<string, object> reqKeyValue)
        {

            //获取当前时间戳
            DateTime now = DateTime.Now;
            // 创建一个时间点为1970年1月1日的DateTime对象
            DateTime unixStartTime = new DateTime(1970, 1, 1);
            // 计算当前本地时间与Unix时间戳的时间差
            TimeSpan timeSpan = now - unixStartTime;
            // 将时间差的总毫秒数作为Unix时间戳输出
            long timestamp = (long)timeSpan.TotalMilliseconds;
            reqKeyValue.Add("accessKey", accessKey);
            //reqKeyValue.Add("secrectKey", secrectKey);
            reqKeyValue.Add("timestamp", timestamp);
            reqKeyValue = reqKeyValue.OrderBy(x => x.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            StringBuilder sb = new StringBuilder();
            foreach (var item in reqKeyValue)
            {
                sb.Append(item.Key);
                sb.Append("=");
                sb.Append(item.Value);
                sb.Append("&");
            }
            //移除左后一个&连接符号
            sb.Remove(sb.Length - 1, 1);
            sb.Append(secrectKey);
            string sign = sb.ToString();
            //SHA256
            sign = sign.SHA256Hash();
            string EncodeUrl = $"{url}?accessKey={accessKey}&timestamp={timestamp}&sign={sign}";
            return EncodeUrl;
        }



        /// <summary>
        /// 通过ONE_LINK提供的接口发送请求获取TOKEN
        /// </summary>
        /// <param name="ol_key"></param>
        /// <returns></returns>
        public string GetToken(string username, string password, string accountType)
        {
            //1.获取Token
            HttpClient httpClient = new HttpClient();
            httpClient.Method = "POST";
            // 设置请求参数
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("https://app.lecangs.com/api/auth/oauth/token");
            sb.AppendFormat($"?username={username}");
            sb.AppendFormat($"&password={password}");
            sb.AppendFormat($"&accountType={accountType}");
            httpClient.Url = sb.ToString();
            string sysReportResul1t = httpClient.Request();
            if (!sysReportResul1t.IsNullOrEmpty())
            {
                return sysReportResul1t;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }


}
